#!/usr/bin/env python
#coding=utf-8

import json
from sqlalchemy import or_
from flask import request, session, current_app
from codingabc.database import db
from codingabc.helpers import log_debug, log_info, log_error, toint
from app.models.menu import Menu
from app.helpers.common import menu, request_url_str



def get_nav_classname(nav):
    """获取导航菜单css class名"""

    if not nav:
        return ''

    parent_menu_id = toint(nav.get('menu_id', '0'))
    if parent_menu_id <= 0:
        return ''

    q = get_query()

    is_request_menu = q.filter(Menu.parent_id == parent_menu_id).first()

    if request.endpoint.split('.')[1] in ('menu_list','menu_add','role_admin','admin_add'):
        return ''

    if is_request_menu:
        session['parent_menu_id'] = parent_menu_id
        return ' class=active'

    if not q.first() and parent_menu_id == session.get('parent_menu_id'):
        return ' class=active'

    return ''

def get_child_nav_classname(child_nav):
    """获取导航菜单css class名"""
    if not child_nav:
        return ''

    child_menu_id = toint(child_nav.get('menu_id', '0'))
    if child_menu_id <= 0:
        return ''

    q = get_query()
    request_menu = q.filter(Menu.menu_id == child_menu_id).first()

    if request_menu:
        session['child_menu_id'] = child_menu_id
        return ' class=active'

    if not q.first() and child_menu_id == session.get('child_menu_id'):
        return ' class=active'

    return ''


def get_sqlalchemy_bind():
    """获取链接数据库url"""

    try:
        sqlalchemy_bind = current_app.config['SQLALCHEMY_BINDS']['jiyuegou']
    except Exception as e:
        log_info('#### get sqlalchemy_bind error:%s'% e)

    return sqlalchemy_bind


def get_query():

    url_str = request_url_str()
    q = db.session.query(Menu.menu_id).\
            filter(Menu.endpoint == url_str).\
            filter(Menu.parent_id > 0)

    return q
